package com.qf.zuulserver11000.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 登陆验证过滤器
 * @author q
 * @version V1.0
 * @date 2022/01/20
 **/
@Component
public class MyZuulAuthFilter extends ZuulFilter {

    /**
     * 过滤器类型
     * @return
     */
    @Override
    public String filterType() {
        //前置过滤器
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器得执行时机
     *      从0开始，值越小优先级越高，默认值是5
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1; //4
    }

    /**
     * 是否执行过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 执行过滤的具体的业务逻辑代码
     *      cookie-->login_token ==>表示已经登录
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        //1、拿request
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        //解决中文乱码问题
        context.getResponse().setContentType("text/html;charset=UTF-8");

        //2、拿cookie
        Cookie[] cookies = request.getCookies();
        if(!ObjectUtils.isEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                if ("login_token".equals(cookie.getName())) {
                    //放行
                    //context.setSendZuulResponse(true);
                    context.set("loginToken",cookie.getValue());
                    //context.setResponseBody("认证通过");
                    //context.setResponseStatusCode(HttpStatus.OK.value()); //200
                    return null;
                }
            }
        }
        //不放行
        context.setSendZuulResponse(false);
        context.setResponseBody("认证未通过，请先登陆");
        context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value()); //401
        return null;
    }
}
